//
//  SchoolDetailViewCommentController.swift
//  HoneyBee
//
//  Created by point on 2018/6/10.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import Photos
import SwiftyJSON

class SchoolDetailViewCommentController: BaseViewController {
    
    typealias endBlock = () -> ()
    var backBlock : endBlock?
   
    
    var schoolID:String = ""
    /// 描述
    fileprivate lazy var contentTextView: HintTextView = HintTextView(frame: CGRect(x: 20, y: 20, width: LayoutCommon.width - 40, height: 150))
    /// 图片选择区
    fileprivate lazy var submitPicView:SchoolCommentSubmitPicView = SchoolCommentSubmitPicView()
    ///用于存储即将上传的数组
    fileprivate var tempUploadImgArr:[String] = [String]()
    ///用于存储即将上传的数组
    fileprivate var uploadImgArr:[UIImage] = [UIImage]()
    
    
    
    lazy var scrollView:UIScrollView =  {
        let scrollView = UIScrollView(frame:CGRect.zero)
        scrollView.bounces = true
        return scrollView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title  = "发表评论"
        setupUI()
    }
}


// MARK: - 交互
extension SchoolDetailViewCommentController:SchoolCommentSubmitPicViewDelegate {
    
    @objc func clickSubmit()  {
        self.hudLoad()
        var dataArr = [Data]()
        uploadImgArr = submitPicView.imgArr
        if uploadImgArr.count == 1 {
            self.loadData()
            return
        } //跳过+号图片
        uploadImgArr.removeLast() //移除 + 号图片
        
        
        
        for img in uploadImgArr {
            let imageData:Data = img.jpegData(compressionQuality: 0.5)!
            dataArr.append(imageData)
        }
        
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { [weak self] (result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].stringValue
            
            let group = DispatchGroup()
            
            for (_,img) in dataArr.enumerated() {
                group.enter()
                let upManager = QNUploadManager()
                upManager?.put(img, key: nil, token: token, complete: { [weak self](info, key, resp) in
                    self?.hudHide()
                    let json = JSON(resp as Any)
                    let url = json["key"].stringValue
                    if url.count > 0 {
                        self?.tempUploadImgArr.append(kqnImageHost + url)
                    }
                    group.leave()
                    }, option: nil)
                
            }
            
            group.notify(queue: DispatchQueue.main) {
                if self?.tempUploadImgArr.count != dataArr.count {
                    self?.hudError()
                }else {
                    self?.loadData()
                }
            }
            
            
        }) { [weak self](error) in
            self?.hudLoad()
        }
        
        
        
        
        /*
         NetworkTools.shareInstance.AFUpload(boolImage: true, URLString: kuploadimg, parameters: dict, data:img, progressing: { (progress) in
         }) { [weak self](result, success) in
         if success {
         let json = JSON(result)
         self?.tempUploadImgArr.append(json["data"].string!)
         }
         group.leave()
         }
         */
        
    }
    
    func loadData() {
        var dict = [
            "content":contentTextView.text,
            "institutionId":schoolID,
            "userId":String(UserInfo.shareInstance.userModel().id)
            ] as [String : Any]
        
        var resourceArr:[[String:Any]] =  [[String:Any]]()
        for val in tempUploadImgArr {
            let dict = [
                "path":val,
                "fileType":0
                ] as [String : Any]
            resourceArr.append(dict)
        }
        if resourceArr.count > 0 {
        dict["resource"] = resourceArr
        }
        let api = kHost + kaddCommentInstitution + String().apiF(time: "111", sign: "222")
        
        TempNetTool.post(api, parameters: dict, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            self?.hudLoadMessage("评论成功")
            self?.backBlock!()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self?.navigationController?.popViewController(animated: true)
               
            }
        }) { [weak self](error) in
            self?.hudError()
        }
        
    }
    //打开图片选择器
    func didSelectItemAt(_ indexPath: IndexPath) {
        
        let vc =  DCAlbumViewController()
        vc.currentMax = submitPicView.imgArr.count
        vc.blockImageArr = { [weak self] (imgs : [UIImage]) -> () in
            self?.submitPicView.configModel(imgs: imgs)
        }
        self.navigationController?.pushViewController(vc, animated: true)
        if PHPhotoLibrary.authorizationStatus() == .authorized {
        } else if PHPhotoLibrary.authorizationStatus() == .denied {
            //用户之前已经拒绝授权
            let alertC = UIAlertController(title: "提示", message: "您之前拒绝了访问相册，请到手机隐私设置", preferredStyle: .alert)
            let sureAction = UIAlertAction(title: "确定", style: .default, handler: { action in
                self.dismiss(animated: true)
            })
            alertC.addAction(sureAction)
            present(alertC, animated: true)
        } else {
            //弹窗授权时监听
            PHPhotoLibrary.requestAuthorization({ status in
                if status == .authorized {
                    DispatchQueue.main.async(execute: {
                        vc.myReload()
                    })
                } else {
                    //拒绝
                    self.dismiss(animated: true)
                }
            })
        }
    }
}

// MARK: - 设置UI
extension SchoolDetailViewCommentController {
    fileprivate func setupUI(){
        let item = UIBarButtonItem(title: "发表评论", style: UIBarButtonItem.Style.plain, target: self, action: #selector(clickSubmit))
        item.tintColor = UIColor.white
        self.navItem.rightBarButtonItem=item
        
        submitPicView.delegate = self
        view.backgroundColor = UIColor.white
        view.addSubview(scrollView)
        scrollView.addSubview(contentTextView)
        scrollView.addSubview(submitPicView)
        scrollView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view).offset(LayoutCommon.navHeight)
            make.bottom.equalToSuperview()
        }
        scrollView.alwaysBounceVertical = true
        //scrollView.contentSize = CGSize(width: CommenLayout.width, height: MyLayout.height - MyLayout.navHeight - MyLayout.bottomSafeHeight + 10)
        scrollView.backgroundColor = UIColor.white
        contentTextView.hint = "在此输入评论"
        contentTextView.backgroundColor = kColorC2
        submitPicView.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.width.equalTo(LayoutCommon.width - 40)
            make.height.equalTo(100)
            make.top.equalTo(contentTextView.snp.bottom).offset(20)
        }
        submitPicView.backgroundColor = UIColor.red
    }
}
